package net.example.model.contract;

import com.oraycn.omcs.utils.BufferUtils;
import com.oraycn.omcs.utils.SerializeUtils;

import net.example.model.CommunicateMediaType;
import net.example.model.CommunicateType;

import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;

/**
 * Created by ZN on 2017/3/6.
 */

public class MediaCommunicateContract {
    private CommunicateMediaType communicateMediaType;
    private CommunicateType communicateType;
    private String tag;

    private int destClientType = -1;

    public int getDestClientType() {
        return destClientType;
    }

    public CommunicateType getCommunicateType() {
        return communicateType;
    }

    public String getTag() {
        return tag;
    }

    public CommunicateMediaType getCommunicateMediaType() {
        return communicateMediaType;
    }

    public MediaCommunicateContract() {

    }

    public MediaCommunicateContract(CommunicateMediaType communicateMediaType, CommunicateType communicateType, String tag, int destClientType) {
        this.communicateMediaType = communicateMediaType;
        this.communicateType = communicateType;
        this.destClientType = destClientType;
        this.tag = tag == null ? "" : tag;
    }

    public void deSeralize(byte[] info) throws Exception {
        ByteBuf buf = BufferUtils.wrappedBuffer(info);
        buf.readInt();
        this.communicateMediaType = CommunicateMediaType.getCommunicateMediaType(buf.readInt());
        this.communicateType = CommunicateType.getCommunicateType(buf.readInt());
        this.destClientType = buf.readInt();
        this.tag = SerializeUtils.readStrIntLen(buf);
    }

    public byte[] toBytes() throws Exception {
        ByteBuf body = BufferUtils.newBuffer();
        byte[] tagData = this.tag.getBytes(StandardCharsets.UTF_8);
        int bodyLen = 4 + 4 + 4 + 4 + 4 + tagData.length;
        body.writeInt(bodyLen);
        body.writeInt(this.communicateMediaType.getType());
        body.writeInt(this.communicateType.getType());
        body.writeInt(this.destClientType);
        body.writeInt(tagData.length);
        body.writeBytes(tagData);
        body.capacity(body.writerIndex());
        return body.array();
    }
}
